package com.marce.remis.flexClient.components
{
	import com.marce.remis.flexClient.control.IconLocator;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	import mx.containers.Box;
	import mx.containers.Panel;
	import mx.core.Application;
	import mx.core.DragSource;
	import mx.core.UITextField;
	import mx.events.FlexEvent;
	import mx.managers.DragManager;

	public class MyPanel extends Panel
	{
		private var moviendo:Boolean;
		private var bloqueada:Boolean;
		
		private var _fija:Boolean;
		
		public function set fija(value:Boolean):void{
			this._fija = value;
			if(value)
				titleIcon = null;
			else
				titleIcon = IconLocator.PUSHPIN_POP;
		}
		
		[Inspectable(category="general",enumeration="true,false",defaultValue="false",type="Boolean")]
		public function get fija():Boolean{
			return _fija;
		}
		
		public function MyPanel()
		{
			super();
			this.addEventListener(FlexEvent.CREATION_COMPLETE,creationCompleteHandler,false,0,true);
		}
		
		private function creationCompleteHandler(event:Event):void{
			this.titleBar.addEventListener(MouseEvent.MOUSE_MOVE,onMove,false,0,true);
			this.titleBar.addEventListener(MouseEvent.MOUSE_UP,onMouseUp,false,0,true);
			this.titleBar.addEventListener(MouseEvent.MOUSE_DOWN,onMouseDown,false,0,true);
			this.titleBar.addEventListener(MouseEvent.CLICK,onClickTitle,false,0,true);
			
			if(fija) titleIcon = null;
			else titleIcon = IconLocator.PUSHPIN_POP;
		}
		
		private function onClickTitle(event:MouseEvent):void{
			if(!(event.target is UITextField) && !fija){
				bloqueada = !bloqueada;
				if(bloqueada) titleIcon = IconLocator.PUSHPIN_PUSHED;
				else titleIcon = IconLocator.PUSHPIN_POP;
			}
		}
		
		private function onMouseUp(event:MouseEvent):void{
			moviendo = false;
		}
		
		private function onMouseDown(event:MouseEvent):void{
			moviendo = false;
		}
		
		private function onMove(event:MouseEvent):void{
			if(!moviendo && event.buttonDown && !bloqueada && !fija){
				moviendo = true;
				var ds:DragSource = new DragSource();
				ds.addData(this,"Panel");
				var box:Box = new Box();
				this.parent.removeChild(this);
				box.addChild(this);
				Application.application.addChild(box);
				this.visible = false;
				DragManager.doDrag(this,ds,event,box,box.x,box.y,1);
				return;
			}
			if(!event.buttonDown){
				moviendo = false;	
			}
			else{
				this.visible = true;
			}
		}
		
	}
}